<template>
  <div id='BacDrugResultTemplate'>
    <Breadcrumb content='药敏模板' />
    <div class='bodyContent'>
      <Splitpanes class='area'>
        <Pane size='40'>
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input type='search' v-model='form.keyvalue' clearable class='vxeInputSearch' @search-click='findList' @clear='findList' @keyup.enter.stop='findList' placeholder='关键字查询'></vxe-input>
              <vxe-button type='text' class='button-blue' @click='findList' icon='vxe-icon-refresh' :loading='loading'>刷新</vxe-button>
              <vxe-button type='text' class='button-blue' @click='addBacDrugResultTemplate' icon='vxe-icon-add'>新增</vxe-button>
              <vxe-button type='text' class='button-blue' @click='saveBacDrugResultTemplate' icon='vxe-icon-save'>保存</vxe-button>
              <vxe-button type='text' class='button-red' @click='deleteBacDrugResultTemplate' icon='vxe-icon-delete'>删除</vxe-button>
            </template>
          </vxe-toolbar>
          <div class='tableBox'>
            <vxe-table ref='tableRef' border='inner' align='left' class='mytable-scrollbar' resizable :loading='loading' height='auto' :data='tableData.filter((data) => !form.keyvalue || (form.keyvalue && ((data.templateNo&& data.templateNo.includes(form.keyvalue))||(data.templateNa&& data.templateNa.includes(form.keyvalue)))))' :edit-config="{trigger: 'click', mode: 'cell'}" :row-config='{ isCurrent: true }' :column-config='{ resizable: true }' show-overflow keep-source :scroll-y='{ enabled: true }' @current-change='tableCellClick' :menu-config='menuConfig' @menu-click='contextMenuClickEvent'>
              <vxe-column type='checkbox' width='26'></vxe-column>
              <vxe-column type='seq' title='#' width='30'></vxe-column>
              <vxe-column field='templateNo' title='编号' width='90' :edit-render="{autofocus: '.vxe-input--inner'}">
                <template #edit="{ row }">
                  <vxe-input v-model="row.templateNo" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field='templateNa' title='名称' min-width='120' :edit-render="{autofocus: '.vxe-input--inner'}">
                <template #edit="{ row }">
                  <vxe-input v-model="row.templateNa" type="text" @blur="addInputCode(row)"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field='inputCode' title='助记符' width='90' :edit-render="{autofocus: '.vxe-input--inner'}">
                <template #edit="{ row }">
                  <vxe-input v-model="row.inputCode" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field='seq' title='排序码' width='90' :edit-render="{autofocus: '.vxe-input--inner'}">
                <template #edit="{ row }">
                  <vxe-input v-model="row.seq" type="text"></vxe-input>
                </template>
              </vxe-column>
              <!-- <vxe-column field='orgName' title='组织机构' min-width='150'> </vxe-column> -->
            </vxe-table>
          </div>
        </Pane>
        <Pane size='60'>
          <Splitpanes horizontal>
            <Pane size='100'>
              <BacDrugResultTempdetail ref='BacDrugResultTempdetailRef' />
            </Pane>
          </Splitpanes>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script lang='ts' setup>
/**引入组件区 ==========*/
import Breadcrumb from '@/components/Breadcrumb.vue'; /**面包屑*/
import { reactive, ref, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import XEClipboard from 'xe-clipboard';
import BacDrugResultTempdetail from './BacDrugResultTempdetail.vue';
import { funBdsJsResult } from '@/utils/Expression'; //函数公式

/**全局变量定义区 ==========*/
let { proxy }: any = getCurrentInstance();
/**左侧表格 */
const loading = ref(false); /**刷新+表格加载*/
const form = reactive({ keyvalue: '' }); /**根据关键字查询*/
const tableRef = ref(null); /**表格ref标记*/
const tableData = reactive([]); /**表格数据*/
const BacDrugResultTempdetailRef = ref(null);/**模板明细组件对象 */
/**右侧表单*/
const BacDrugResultTemplateFormRef = ref<InstanceType<typeof BacDrugResultTemplateForm>>();
let currentRow: any = reactive({ id: '', code: '' });
let curIndex = ref(-1);/**保存时记录当前选中索引，更换新完数据后 再次选中改行 */


/**vxe-table 表格右击属性*/
const menuConfig = reactive<VxeTablePropTypes.MenuConfig<RowVO>>({
  header: {
    options: [
      [
        { code: 'hideColumn', name: '隐藏列', disabled: false },
        { code: 'showAllColumn', name: '取消所有隐藏列', disabled: false }
      ]
    ]
  },
  body: {
    options: [
      [
        { code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy', disabled: false },
        { code: 'reload', name: '刷新', disabled: false },
        { code: 'remove', name: '删除', disabled: false },
        { code: 'save', name: '保存', prefixIcon: 'vxe-icon-save', disabled: false }
      ]
    ]
  },
  visibleMethod({ options, column }) {
    const isDisabled = !column;
    options.forEach((list) => {
      list.forEach((item) => {
        item.disabled = isDisabled;
      });
    });
    return true;
  }
});

/**方法定义区 =============*/
onMounted(() => {
  findList(); /**获取药敏模板表格数据*/
});

/**获取 药敏模板表格数据*/
const findList = () => {
  loading.value = true;
  tableData.length = 0; /**放入数据前清空数据*/
  const url = '/api/bac/bac-drug-result-template/findBacDrugResultTemplateList';
  proxy.$http
    /**注意此处的数据条数*/
    .get(url, { keyWords: form.keyvalue })
    .then(async (res: any) => {
      tableData.push(...res.data);
      loading.value = false;
      if (res && res.data && res.data.length > 0) {
        const newSelRow = curIndex.value >= 0 && curIndex.value <= res.data.length - 1 ? res.data[curIndex.value] : res.data[0];
        tableCellClick({ row: newSelRow });
        const $table = tableRef.value;
        if ($table) {
          currentRow.id = '';
          await $table.setCurrentRow(newSelRow);
        }
      }
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取药敏模板列表数据异常', VxeNotifyType.error);
    });
};

/**新增药敏模板*/
async function addBacDrugResultTemplate() {
  (proxy.$refs.tableRef as any).clearCurrentRow();
  const row = {
    id: '',
    templateNo: '',
    templateNa: '',
    inputCode: '',
    seq: (tableData.length + 1) + ''
  };
  tableData.push(row);
  await tableRef.value?.setCurrentRow(row);
  await tableRef.value?.setEditCell(row, 'templateNo');
}

/**保存药敏模板*/
function saveBacDrugResultTemplate() {
  loading.value = true;
  const row = tableRef.value?.getCurrentRecord();
  curIndex.value = tableRef.value?.getRowIndex(row);
  proxy.$http
    .post('/api/bac/bac-drug-result-template/batchSaveBacDrugResultTemplate', tableData)
    .then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        findList();
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
    });
}

/**删除药敏模板*/
async function deleteBacDrugResultTemplate() {
  const arr = await tableRef.value?.getCheckboxRecords(true);
  if (!arr || arr.length <= 0) {
    VxeMessage('请勾选要删除的药敏模板', VxeNotifyType.info);
    loading.value = false;
    return;
  } else {
    proxy
      .$confirm('确定删除选中数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        loading.value = true;
        const url = '/api/bac/bac-drug-result-template/batchDeleteBacDrugResultTemplate';
        const arr = await tableRef.value?.getCheckboxRecords(true);
        if (arr && arr.length > 0) {
          proxy.$http
            .post(url, arr)
            .then((res: any) => {
              if (res.status.code === 1) {
                VxeMessage('删除药敏模板成功', VxeNotifyType.success);
                findList();
              } else {
                VxeMessage('删除药敏模板失败', VxeNotifyType.error);
              }
              loading.value = false;
            })
            .catch((err: any) => {
              loading.value = false;
            });
        } else {
          loading.value = false;
        }
      });
  }
}

// 表格右击菜单项
const contextMenuClickEvent: VxeTableEvents.MenuClick<RowVO> = ({ menu, row, column }) => {
  const $table = tableRef.value;
  if (table) {
    switch (menu.code) {
      case 'hideColumn':
        $table.hideColumn(column);
        break;
      case 'showAllColumn':
        $table.resetColumn(true);
        break;
      case 'copy':
        if (XEClipboard.copy((row as any)[column.field])) {
          VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
        }
        break;
      case 'reload':
        findList();
        break;
      case 'insertAt':
        $table.insertAt({}, row || -1).then(({ row }) => {
          $table.setEditCell(row, column || 'name');
        });
        break;
      case 'remove':
        $deleteBacDrugResultTemplate();
        break;
      case 'save':
        saveBacDrugResultTemplate();
        break;
    }
  }
};

/**表格选中当前行*/
function tableCellClick({ row }) {
  Object.assign(currentRow, row);
  BacDrugResultTempdetailRef.value?.tempSelectChange(currentRow);
  proxy.$forceUpdate();
}
// 填写仪器名称 自动生成助记符
function addInputCode(row) {
  row.inputCode = funBdsJsResult('firstPinYinFun', row.templateNa);
}
</script>
<style lang='scss' scoped>
#BacDrugResultTemplate {
  width: 100%;
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .tableBox {
        height: calc(100% - 40px);
      }
    }
  }
}
</style>